#include "inc.h"

void* pfunc(void *para);

int main()
{
	int ser_socket = 0;
	int con_socket = 0;
	struct sockaddr_in ser_addr;
	struct sockaddr_in con_addr;
	int ret = 0;
	pthread_t pid = 0;
	socklen_t addrlen = sizeof(struct sockaddr);
	
	memset(&ser_addr, 0, sizeof(ser_addr));
	memset(&ser_addr, 0, sizeof(con_addr));

	ser_addr.sin_family = AF_INET;
	ser_addr.sin_port = htons(5555);
	ser_addr.sin_addr.s_addr = htonl(INADDR_ANY);
	
	ser_socket = socket(AF_INET, SOCK_STREAM, 0);
	if (ser_socket == -1)
		printf("%s %d error\n", __FUNCTION__, __LINE__);
	
	ret = bind(ser_socket, (struct sockaddr *)&ser_addr, sizeof(ser_addr));
	if (ret != 0)
		printf("%s, %d error \n", __FUNCTION__, __LINE__);
	
	ret = listen(ser_socket, 100);
	if (ret != 0)
		printf("%s, %d error \n", __FUNCTION__, __LINE__);

	while (1)
	{
		con_socket = accept(ser_socket, (struct sockaddr *)&con_addr, &addrlen);
		if (con_socket != -1)
		{
			pthread_create(&pid, NULL, pfunc, &con_socket);
		} 
	}

	close(ser_socket);
	
	return 0;
}


void* pfunc(void *para)
{
	int ret = 0;
	char msg[20] = {0};
	int * con_socket = (int *)para;
	pthread_detach(pthread_self());

	ret = recv(*con_socket, msg, sizeof(msg), 0);
	if (ret != sizeof(msg))
		printf("%s %d \n", __FUNCTION__, __LINE__);
	printf("server redv %s \n", msg);

	memset(msg, 0, sizeof(msg));
	strcpy(msg, "I 'am server\n");
	printf("......%s \n", msg);
	ret = send(*con_socket, msg, sizeof(msg), 0);
	printf("......ret = %d \n", ret);
	if (ret != sizeof(msg))
		printf("%s %d error\n", __FUNCTION__, __LINE__);
	close(*con_socket);
	return NULL;
}
	
